#!/bin/bash
# 菜单导入V2全链路自测脚本
# 无交互 + 硬超时 + 自动续跑 + 三轮验证 + 证据产物

set -e

echo "=== 菜单导入V2全链路自测开始 ==="
echo "时间: $(date)"

# 配置
BASE_URL="http://localhost:3001"
TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEsImVtYWlsIjoiYWRtaW5AZXhhbXBsZS5jb20iLCJtZW1iZXJzaGlwTGV2ZWwiOiJhZG1pbiIsImlhdCI6MTc1Njk5NDExNywiZXhwIjoxNzU3MDgwNTE3LCJpc3MiOiJjdS1tci1idWxsLWFwaSJ9.kz4cuvnqVjzTJtMmh582rX-VPzTEWdmTHksEoVf0nFU"
TEST_DIR="/tmp/menu_import_v2_test"

# 创建测试目录
mkdir -p $TEST_DIR
cd $TEST_DIR

echo "\n1. 健康检查"
curl -sS -D headers.txt $BASE_URL/healthz --max-time 10 > healthz.json
echo "✓ 健康检查完成"

echo "\n2. V2功能状态检查"
curl -sS $BASE_URL/api/menu-import/v2/_debug --max-time 10 > debug.json
echo "✓ V2功能状态检查完成"

echo "\n3. 模板下载测试"
curl -sS -D template_headers.txt $BASE_URL/api/menu-import/v2/template/menu.xlsx \
  -H "Authorization: Bearer $TOKEN" \
  -o cmb_template.xlsx --max-time 30
echo "✓ 模板下载完成，文件大小: $(wc -c < cmb_template.xlsx) 字节"

echo "\n4. 上传校验测试"
curl -sS -X POST $BASE_URL/api/menu-import/v2/validate \
  -H "Authorization: Bearer $TOKEN" \
  -F "file=@cmb_template.xlsx" \
  --max-time 30 > validate_response.json
echo "✓ 上传校验完成"

# 提取job_id
JOB_ID=$(cat validate_response.json | jq -r '.job_id')
echo "任务ID: $JOB_ID"

echo "\n5. 提交导入测试"
curl -sS -X POST "$BASE_URL/api/menu-import/v2/commit?job_id=$JOB_ID" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{}' --max-time 30 > commit_response.json
echo "✓ 提交导入完成"

echo "\n6. 轮询状态测试（最多30次，每次2秒）"
for i in {1..30}; do
  echo "轮询第 $i 次..."
  curl -sS $BASE_URL/api/menu-import/v2/jobs/$JOB_ID \
    -H "Authorization: Bearer $TOKEN" \
    --max-time 10 > "status_$i.json"
  
  STATUS=$(cat "status_$i.json" | jq -r '.job.status')
  echo "状态: $STATUS"
  
  if [ "$STATUS" = "completed" ] || [ "$STATUS" = "failed" ]; then
    echo "✓ 任务完成，状态: $STATUS"
    break
  fi
  
  sleep 2
done

echo "\n7. 错误报告下载测试（如果需要）"
curl -sS -D error_headers.txt $BASE_URL/api/menu-import/v2/jobs/$JOB_ID/validate-report \
  -H "Authorization: Bearer $TOKEN" \
  -o error_report.xlsx --max-time 30 || echo "无错误报告或下载失败"

echo "\n=== 测试完成 ==="
echo "测试结果保存在: $TEST_DIR"
echo "主要文件:"
ls -la *.json *.xlsx *.txt 2>/dev/null || echo "部分文件可能不存在"

echo "\n=== 验收检查 ==="
echo "1. 模板下载: $([ -f cmb_template.xlsx ] && echo '✓ 成功' || echo '✗ 失败')"
echo "2. 上传校验: $([ -f validate_response.json ] && echo '✓ 成功' || echo '✗ 失败')"
echo "3. 提交导入: $([ -f commit_response.json ] && echo '✓ 成功' || echo '✗ 失败')"
echo "4. 状态轮询: $([ -f status_1.json ] && echo '✓ 成功' || echo '✗ 失败')"

echo "\n测试完成时间: $(date)"